package org.demo.dao.repository;

import org.demo.dao.entity.Detail;
import org.demo.dao.mapper.DetailMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public class DetailRepository {

    private static final Logger logger = LoggerFactory.getLogger(DetailRepository.class);

    @Autowired
    private DetailMapper detailDao;

    /**
     * 测试事务3，基于唯一性索引的S锁
     */
    @Transactional
    void transaction3() throws InterruptedException {
        Long code = 100309L;
        Detail list = detailDao.selectById(code);
        logger.info("查询数据:" + list);
        synchronized (list) {
            list.wait();
        }
    }

    /**
     * 测试事务1，验证获取S锁，且建立在GAP锁基础上
     */
    @Transactional
    public void transaction1(String code) throws InterruptedException {
        List<Detail> list = detailDao.selectByCode(code);
        for(Detail d:list){
            logger.info("查询数据:" + d);
        }
        synchronized (list) {
            list.wait();
        }
    }


    /**
     * 测试事务2，数据插入
     * @throws InterruptedException
     */
    @Transactional
    public void transaction2(Boolean wait, String code) throws InterruptedException {
        Detail detail = new Detail();
        detail.setCode(code);
        detail.setDetail("yyyyyyyy");
        detailDao.insert(detail);
        detail.setCode(code);

//        double a = 1/0;
        detail.setDetail("yyyyyy234545");
        detailDao.insert(detail);
        if(wait) {
            synchronized (detail) {
                detail.wait();
            }
        }
    }

    @Transactional
    public void transaction4(Boolean wait, String code) throws InterruptedException {
        detailDao.delete(code);
        if(wait) {
            synchronized (detailDao) {
                detailDao.wait();
            }
        }
    }
}
